package com.pan.service.impl;

import com.pan.dao.coupon.CouponSelectDao;
import com.pan.dao.coupon.CouponUpdateDao;
import com.pan.entity.Coupon;
import com.pan.entity.Result;
import com.pan.enume.ResultEnum;
import com.pan.service.OperationCouponService;
import com.pan.tools.RedisTools;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("operationCouponService")
    public class OperationCouponServiceImpl implements OperationCouponService {

        @Resource
        private CouponSelectDao couponSelectDao;

        @Resource
        private CouponUpdateDao couponUpdateDao;

        @Resource
        private RedisTools redisTools;

    @Override
    public Result setSeckillCoupon(String adminTicket, Long couponId){
        Coupon coupon = couponSelectDao.selectById(couponId);
        if (coupon == null){
            return new Result(ResultEnum.NOT_FOUND_ERROR);
        }
//        if (coupon.getStartDate() != null){
//            return new Result(403,"该优惠券已经发布");
//        }
        Timestamp endDate = coupon.getEndDate();
        Long nowTime = System.currentTimeMillis();
        if (nowTime > endDate.getTime()){
            return new Result(403,"该结束时间已经过去");
        }
        Timestamp startDate = new Timestamp(nowTime);
        couponUpdateDao.updateStartDate(couponId,startDate);
        couponUpdateDao.updateEndDate(couponId,new Timestamp(endDate.getTime()));
        couponUpdateDao.updateReceiveCount(couponId,0);
        couponUpdateDao.updateUseCount(couponId,0);
        Map<Object,Object> map = new HashMap<>();
        map.put("count",String.valueOf(coupon.getPublishCount()));
        map.put("userLimit",String.valueOf(coupon.getUserLimit()));
        map.put("growthLimit",String.valueOf(coupon.getGrowthLimit()));
        redisTools.hset("seckillCoupon:"+couponId,map);
        Map<String,String> mapUser = new HashMap<>();
        mapUser.put("0","0");
        redisTools.hset("userSeckillCoupon:"+couponId,mapUser);
        Long liveTime = endDate.getTime() - nowTime;
        redisTools.expire("userSeckillCoupon:"+couponId,liveTime);
        return new Result(ResultEnum.SUCCESS);

    }

}
